package com.zdw.zfw.admin.modular.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import com.zdw.zfw.admin.modular.system.service.ISysCaptchaService;
import com.zdw.zfw.core.common.utils.IOUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import wiki.xsx.core.handler.StringHandler;
import wiki.xsx.core.util.RedisUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码的Service实现类
 *
 * @author zdw
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysCaptchaServiceImpl implements ISysCaptchaService {

    /**
     * 验证码生成器
     */
    private final Producer producer;

    /**
     * 验证码凭据的key
     */
    private static final String CAPTCHA_TOKEN = "captcha_token";

    /**
     * 生成验证码
     *
     * @param response request
     * @param request  request
     */
    @Override
    public void generateCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 生成绑定验证码的随机id(凭据)
        String captchaToke = IdUtil.simpleUUID();
        // 将生成的id和验证码存入缓存(redis)方便验证 时效为3分钟
        StringHandler stringHandler = RedisUtil.getStringHandler();
        stringHandler.set(captchaToke, text,180L, TimeUnit.SECONDS);

        // 将验证码的凭据存入cookie返回给客户端
        response.addCookie(new Cookie(CAPTCHA_TOKEN, captchaToke));
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @Override
    public String checkCaptcha(String cookie, String captcha){
        if (cookie == null){
            return "客户端凭据出错，请刷新验证码";
        }

        // 根据凭据从缓存中读取验证码
        StringHandler stringHandler = RedisUtil.getStringHandler();
        String captchaInCache = stringHandler.get(cookie);

        if (StringUtils.isEmpty(captchaInCache)) {
            return "验证码过期，请刷新验证码";
        }

        // 匹配验证码
        boolean isEquals = captchaInCache.equals(captcha);
        return isEquals ? "" : "验证码错误" ;
    }
}
